package com.wbhz.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;

import com.wbhz.dao.DeptDao;
import com.wbhz.dao.mapper.DeptMapper;
import com.wbhz.entity.Dept;
import com.wbhz.util.JdbcTemplate;

public class DeptDaoImpl implements DeptDao {
	private static Logger logger = Logger.getLogger(DeptDaoImpl.class);

	public int insertDept(Dept d) throws SQLException {
		logger.debug("在DeptDaoImpl类中，调用insertDept方法");
		String sql = "insert into t_dept values (?,?,?,?,now());";
		String[] objects = {d.getDno(), d.getDname(), d.getDloc(), d.getDmanager()};
		int count = JdbcTemplate.executeUpdate(sql, objects);
		logger.info("执行insertDept返回结果是："+count);
		return count;
	}
	// 若该部门下还有员工关联，不允许删除！
	public int delete(Dept d)  throws SQLException {
		logger.debug("在DeptDaoImpl类中，调用delete方法");
		String sql="delete from t_dept where t_dept_no=?";//所有的占位符必须是英文的问号
		String[] objects = {d.getDno()};
		int count = JdbcTemplate.executeUpdate(sql, objects);
		logger.info("执行delete返回结果是："+count);
		return count;
	}
	
	public int update(Dept d) throws SQLException{
		logger.debug("在DeptDaoImpl类中，调用update方法");
		String sql="UPDATE t_dept set t_dept_name=?, t_dept_loc=?, t_dept_manager=? where t_dept_no=?";
		String[] objects = {d.getDname(), d.getDloc(), d.getDmanager(), d.getDno()};
		int count = JdbcTemplate.executeUpdate(sql, objects);
		logger.info("执行update返回结果是："+count);
		return count;
	}
	
	public int showInfo(Dept d) throws SQLException{
		logger.debug("在DeptDaoImpl类中，调用update方法");
		String sql="select * from t_dept where t_dept_no=?";
		String[] objects = {d.getDno()};
		int count = JdbcTemplate.executeUpdate(sql, objects);
		logger.info("执行showInfo返回结果是："+count);
		return count;
	}
	
	public List<Dept> getAllMoods() throws SQLException {
		logger.debug("在DeptDaoImpl类中，调用getAllMoods方法");
		String sql="select * from t_dept";
		return JdbcTemplate.executeQuery(sql, new DeptMapper(), null);
	}
	
	public List<Dept> getMoodsPerPage(int currentPage, int size) throws SQLException {
		logger.debug("在DeptDaoImpl类中，调用getMoodsPerPage方法");
		
		int begin = (currentPage-1)*size; //当前页-1 再乘以显示的大小
		//如果使用数据分页，只能使用字符串拼接的方式
		String sql="select * from t_dept LIMIT "+begin+" , "+size;
		//limit 不支持占位符
		//String sql="select * from t_mood LIMIT ?,?";
		//String[] objs= {begin+"",size+""};
		return JdbcTemplate.executeQuery(sql, new DeptMapper(), null);
	}

}
